package com.situ.mall.controller;

import com.situ.mall.util.AliOSSUtil;
import com.situ.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/service")
public class UploadController {
    //所有上传的图片
    public static final String UPLOAD_IMAGE = "uploadImage";
    //所有上传而且保存到数据库中图片
    public static final String UPLOAD_IMAGE_TO_DB = "uploadImageToDB";
    @Autowired
    private RedisTemplate redisTemplate;

    //MultipartFile file封装了所有和图片上传相关信息
    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {
        //3c6f493281204d5c9cad2271fdf8ff31
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //a.png
        String filename = file.getOriginalFilename();
        //.png
        String extension = filename.substring(filename.lastIndexOf("."));
        //3c6f493281204d5c9cad2271fdf8ff31.png
        String newFilename = uuid + extension;
        String url = "";
        try {
            url = AliOSSUtil.uploadFile(newFilename, file.getInputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        redisTemplate.opsForSet().add(UPLOAD_IMAGE, url);
        return Result.ok("", url);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        //35bdc4b9-d8bf-4aab-a151-4f4ee0186984
        System.out.println(uuid);
        //3c6f493281204d5c9cad2271fdf8ff31
        System.out.println(uuid.replace("-", ""));
    }
}
